<template>
  <div class="archive-approval-request-management-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>档案审批请求管理</span>
      </div>
      <div class="search-bar">
        <el-select v-model="searchStatus" placeholder="按状态筛选" clearable @change="fetchRequests">
          <el-option label="待处理" value="pending"></el-option>
          <el-option label="已批准" value="approved"></el-option>
          <el-option label="已拒绝" value="rejected"></el-option>
        </el-select>
        <el-select v-model="searchQuery" placeholder="按请求类型筛选" clearable @change="fetchRequests" style="margin-left: 10px;">
          <el-option label="密级调整" value="confidentiality_level_adjustment"></el-option>
          <el-option label="纸质档案调取" value="paper_archive_retrieval"></el-option>
          <el-option label="档案修改" value="modification"></el-option>
        </el-select>
        <!-- <el-input placeholder="搜索备注内容" v-model="searchQuery" class="input-with-select" @keyup.enter.native="fetchRequests" style="margin-left: 10px;">
          <el-button slot="append" icon="el-icon-search" @click="fetchRequests"></el-button>
        </el-input> -->
      </div>
      <el-table :data="requests" style="width: 100%">
        <el-table-column prop="requestId" label="请求ID" width="80"></el-table-column>
        <el-table-column prop="archiveTitle" label="档案标题" width="200" show-overflow-tooltip></el-table-column>
        <el-table-column prop="requestType" label="请求类型" width="150" :formatter="requestTypeFormatter"></el-table-column>
        <el-table-column prop="requestedValue" label="请求值" width="120" show-overflow-tooltip></el-table-column>
        <el-table-column prop="requesterName" label="申请人" width="120"></el-table-column>
        <el-table-column prop="requestTime" label="请求时间" width="180"></el-table-column>
        <el-table-column prop="status" label="状态" width="100" :formatter="statusFormatter"></el-table-column>
        <el-table-column prop="approverName" label="审批人" width="120"></el-table-column>
        <el-table-column prop="approvalTime" label="审批时间" width="180"></el-table-column>
        <el-table-column prop="notes" label="备注" show-overflow-tooltip></el-table-column>
        <el-table-column label="操作" width="180">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="success"
              @click="handleApprove(scope.row)"
              v-if="scope.row.status === 'pending' && hasPermission('企业领导')">批准</el-button>
            <el-button
              size="mini"
              type="danger"
              @click="handleReject(scope.row)"
              v-if="scope.row.status === 'pending' && hasPermission('企业领导')">拒绝</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="totalRequests">
      </el-pagination>
    </el-card>

    <!-- Dialog for Notes when Approving/Rejecting -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="30%"
      :before-close="handleCloseNotesDialog">
      <el-input
        type="textarea"
        :rows="4"
        placeholder="请输入备注"
        v-model="notes">
      </el-input>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleCloseNotesDialog">取 消</el-button>
        <el-button type="primary" @click="confirmAction">确 定</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
import service from '@/utils/request';

export default {
  name: 'ArchiveApprovalRequestManagement',
  data() {
    return {
      requests: [],
      currentPage: 1,
      pageSize: 10,
      totalRequests: 0,
      searchStatus: '',
      // searchRequestType: '',
      searchQuery: '',
      userRole: '',
      dialogVisible: false,
      dialogTitle: '',
      notes: '',
      currentActionRequest: null, // Stores the request being acted upon
      actionType: '' // 'approve' or 'reject'
    };
  },
  created() {
    const user = JSON.parse(localStorage.getItem('user'));
    if (user && user.role) {
      this.userRole = user.role;
    }
    this.fetchRequests();
  },
  methods: {
    hasPermission(...roles) {
      return roles.includes(this.userRole);
    },
    requestTypeFormatter(row, column, cellValue) {
      const typeMap = {
        'confidentiality_level_adjustment': '密级调整',
        'paper_archive_retrieval': '纸质档案调取',
        'modification': '档案修改'
      };
      return typeMap[cellValue] || cellValue;
    },
    statusFormatter(row, column, cellValue) {
      const statusMap = {
        'pending': '待处理',
        'approved': '已批准',
        'rejected': '已拒绝'
      };
      return statusMap[cellValue] || cellValue;
    },
    fetchRequests() {
      service.get('/archive-approval/list', {
        params: {
          pageNum: this.currentPage,
          pageSize: this.pageSize,
          status: this.searchStatus,
          search: this.searchQuery
        }
      })
      .then(res => {
        if (res.data.code === 200) {
          this.requests = res.data.data.records;
          this.totalRequests = res.data.data.total;
        } else {
          this.$message.error(res.data.message || '获取审批请求列表失败');
        }
      })
      .catch(error => {
        console.error("Error fetching approval requests:", error);
        this.$message.error('获取审批请求列表失败');
      });
    },
    handleApprove(row) {
      this.currentActionRequest = row;
      this.actionType = 'approve';
      this.dialogTitle = '批准请求';
      this.dialogVisible = true;
    },
    handleReject(row) {
      this.currentActionRequest = row;
      this.actionType = 'reject';
      this.dialogTitle = '拒绝请求';
      this.dialogVisible = true;
    },
    confirmAction() {
      if (!this.currentActionRequest) return;

      const url = this.actionType === 'approve' ? `/archive-approval/approve/${this.currentActionRequest.requestId}` : `/archive-approval/reject/${this.currentActionRequest.requestId}`;
      const payload = this.notes; // Send notes directly as request body for POST

      service.post(url, payload, {
        headers: {
          'Content-Type': 'text/plain' // Explicitly set content type for raw string body
        }
      })
      .then(res => {
        if (res.data.code === 200) {
          this.$message.success(res.data.message || `${this.dialogTitle}成功`);
          this.fetchRequests(); // Refresh the list
          this.handleCloseNotesDialog();
        } else {
          this.$message.error(res.data.message || `${this.dialogTitle}失败`);
        }
      })
      .catch(error => {
        console.error(`${this.dialogTitle} failed:`, error);
        this.$message.error(`${this.dialogTitle}失败`);
      });
    },
    handleCloseNotesDialog() {
      this.dialogVisible = false;
      this.dialogTitle = '';
      this.notes = '';
      this.currentActionRequest = null;
      this.actionType = '';
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.fetchRequests();
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.fetchRequests();
    }
  }
}
</script>

<style scoped>
.archive-approval-request-management-container {
  padding: 20px;
}
.search-bar {
  margin-bottom: 20px;
  display: flex;
  gap: 10px;
}
.input-with-select {
  width: 300px;
}
.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}
.clearfix:after {
  clear: both
}
.box-card {
  width: 100%;
}
</style> 